<template>
  <div class="payment-page">
    <div class="payment-container">
      <div class="payment-status">
        <div class="amount">￥{{ orderInfo.buyMoneyAll }}</div>
        <div class="status-text">{{ getStatusText }}</div>
        <div class="countdown">
          <span class="label">支付剩余时间：</span>
          <span class="time" :class="{ 'warning': countdown <= 300 }">{{ formatTime(countdown) }}</span>
        </div>
      </div>

      <div class="qr-code" v-if="paymentQRCode">
        <img :src="paymentQRCode" alt="支付二维码" />
        <div class="tip">请使用{{ paymentMethod === 'wxpay' ? '微信' : '支付宝' }}扫码支付</div>
      </div>

      <div class="order-info">
        <div class="info-item">
          <span class="label">订单编号：</span>
          <span class="value">{{ orderInfo.orderNumber }}</span>
        </div>
        <div class="info-item">
          <span class="label">商品名称：</span>
          <span class="value">{{ orderInfo.productTitle }}</span>
        </div>
        <div class="info-item">
          <span class="label">支付方式：</span>
          <span class="value">{{ paymentMethod === 'wxpay' ? '微信支付' : '支付宝支付' }}</span>
        </div>
      </div>

      <div class="actions">
        <el-button @click="cancelPayment" :disabled="submitting">取消支付</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderDetail, queryPaymentStatus, cancelOrder } from '@/api/payment'

const route = useRoute()
const router = useRouter()

// 订单信息
const orderInfo = ref({
  orderNumber: '',
  productTitle: '',
  buyMoneyAll: 0,
  payStatus: 0
})

// 支付二维码
const paymentQRCode = ref('')
// 支付方式
const paymentMethod = ref(route.query.paymentMethod || 'wxpay')
// 提交状态
const submitting = ref(false)

// 倒计时相关
const PAYMENT_TIMEOUT = 15 * 60 // 15分钟支付超时
const countdown = ref(PAYMENT_TIMEOUT)
let countdownTimer: number | null = null

// 格式化时间
const formatTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 状态文本
const getStatusText = computed(() => {
  switch (orderInfo.value.payStatus) {
    case 0:
      return '等待支付'
    case 1:
      return '支付处理中'
    case 9:
      return '支付成功'
    default:
      return '未知状态'
  }
})

// 轮询定时器
let pollTimer: number | null = null

// 获取订单详情
const getOrder = async () => {
  try {
    const res = await getOrderDetail(route.query.orderId as string)
    orderInfo.value = res.data
  } catch (error) {
    console.error('获取订单信息失败', error)
    ElMessage.error('获取订单信息失败')
  }
}

// 查询支付状态
const checkPaymentStatus = async () => {
  try {
    const res = await queryPaymentStatus(route.query.orderId as string)
    if (res.data.status === 9) {
      // 支付成功
      clearInterval(pollTimer as number)
      clearInterval(countdownTimer as number)
      ElMessage.success('支付成功')
      router.push('/order/list')
    }
  } catch (error) {
    console.error('查询支付状态失败', error)
  }
}

// 取消支付
const cancelPayment = () => {
  ElMessageBox.confirm('确定要取消支付吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      submitting.value = true
      try {
        const res = await cancelOrder(route.query.orderId as string)
        if (res.data.code === 0) {
          if (pollTimer) clearInterval(pollTimer)
          if (countdownTimer) clearInterval(countdownTimer)
          ElMessage.success('订单已取消')
          setTimeout(() => {
            router.push('/')
          }, 500)
        } else {
          throw new Error(res.data?.msg || '取消订单失败')
        }
      } catch (error: any) {
        ElMessage.error(error.message || '取消订单失败，请稍后重试')
      } finally {
        submitting.value = false
      }
    })
    .catch(() => {
      // 用户点击取消按钮，不做任何操作
    })
}

// 处理支付超时
const handlePaymentTimeout = async () => {
  clearInterval(pollTimer as number)
  clearInterval(countdownTimer as number)
  ElMessage.warning('支付超时，订单已自动取消')
  await cancelOrder(route.query.orderId as string)
  router.push('/order/list')
}

onMounted(async () => {
  await getOrder()
  // 开始轮询支付状态
  pollTimer = setInterval(checkPaymentStatus, 3000) as unknown as number

  // 开始倒计时
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      handlePaymentTimeout()
    }
  }, 1000) as unknown as number
})

onUnmounted(() => {
  if (pollTimer) {
    clearInterval(pollTimer)
  }
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style lang="less" scoped>
.payment-page {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;

  .payment-container {
    max-width: 600px;
    width: 100%;
    margin: 0 auto;
    background: #fff;
    padding: 40px;
    border-radius: 16px;
    text-align: center;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
    }

    .payment-status {
      margin-bottom: 40px;

      .amount {
        font-size: 42px;
        font-weight: bold;
        color: #ff4d4f;
        margin-bottom: 15px;
        text-shadow: 0 2px 4px rgba(255, 77, 79, 0.2);
        animation: fadeInDown 0.5s ease;
      }

      .status-text {
        font-size: 20px;
        color: #333;
        margin-bottom: 15px;
        font-weight: 500;
      }

      .countdown {
        font-size: 16px;
        background: #f8f9fa;
        padding: 10px 20px;
        border-radius: 20px;
        display: inline-block;

        .label {
          color: #666;
        }

        .time {
          color: #333;
          font-weight: bold;
          margin-left: 5px;

          &.warning {
            color: #ff4d4f;
            animation: pulse 1s infinite;
          }
        }
      }
    }

    .qr-code {
      margin-bottom: 40px;
      padding: 20px;
      background: #f8f9fa;
      border-radius: 12px;
      transition: all 0.3s ease;

      &:hover {
        background: #fff;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
      }

      img {
        width: 220px;
        height: 220px;
        margin-bottom: 15px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      }

      .tip {
        color: #666;
        font-size: 15px;
      }
    }

    .order-info {
      text-align: left;
      padding: 25px;
      background: #f8f9fa;
      border-radius: 12px;
      margin-bottom: 30px;

      .info-item {
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        line-height: 1.5;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          color: #666;
          margin-right: 10px;
          min-width: 80px;
        }

        .value {
          color: #333;
          font-weight: 500;
          flex: 1;
          word-break: break-all;
        }
      }
    }

    .actions {
      margin-top: 30px;

      .el-button {
        padding: 12px 30px;
        font-size: 16px;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        &:active {
          transform: translateY(0);
        }
      }
    }
  }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.5;
  }

  100% {
    opacity: 1;
  }
}

:global(.el-message-box) {
  border-radius: 12px !important;
  padding: 0 !important;
  overflow: hidden !important;
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  min-width: 420px !important;
  background: #fff !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;

  .el-message-box__header {
    padding: 20px !important;
    background: #f8f9fa !important;
    margin: 0 !important;

    .el-message-box__title {
      font-size: 18px !important;
      font-weight: 600 !important;
    }
  }

  .el-message-box__content {
    padding: 30px 20px !important;
    text-align: center !important;
    font-size: 16px !important;
  }

  .el-message-box__btns {
    padding: 20px !important;
    border-top: 1px solid #eee !important;
    text-align: center !important;

    .el-button {
      min-width: 100px !important;
      padding: 10px 20px !important;
      border-radius: 6px !important;
      font-size: 15px !important;
      margin: 0 10px !important;
      transition: all 0.3s ease !important;

      &:hover {
        transform: translateY(-2px) !important;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
      }
    }
  }
}

:global(.el-overlay) {
  backdrop-filter: blur(5px) !important;
  background-color: rgba(0, 0, 0, 0.6) !important;
}
</style>
